<template>
  <div>
    <div slot="com_header"><bread></bread></div>
    <div slot="com_con">
      <!-- 分配权限的弹窗 -->
      <el-dialog title="分配权限" :visible.sync="dialogRights" width="65%">
        <!-- <el-tree
          :props="treeList"
          :load="loadNode"
          lazy
          show-checkbox
          @check-change="handleCheckChange"
        >
        </el-tree> -->
        <el-tree
          :data="treeList"
          :props="treeProps"
          show-checkbox
          @node-click="handleNodeClick"
          default-expand-all
          node-key="id"
          ref="tree"
          :highlight-current="true"
        ></el-tree>
        <div slot="footer" class="dialog-footer">
          <el-button @click="clearTree()">清空</el-button>
          <el-button @click="close">取 消</el-button>
          <el-button type="primary" @click="saveTree">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 添加角色的弹窗 -->
      <el-dialog title="添加角色" :visible.sync="addForm">
        <el-form :model="addRole">
          <el-form-item label="角色名称" label-width="120">
            <el-input v-model="addRole.roleName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" label-width="120">
            <el-input v-model="addRole.roleDesc" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addForm = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </div>
      </el-dialog>
      <el-table :data="tableData" border style="width: 100%">
        <!-- 下拉信息 -->
        <el-table-column type="expand">
          <template slot-scope="{ row }">
            <el-row
              v-for="(item, index) in row.children"
              :key="item.id"
              style="
                border-bottom: 1px solid red;
                display: flex;
                align-items: center;
              "
            >
              <el-col :span="8" style="">
                <el-tag type="">{{ item.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="16">
                <el-row v-for="two in item.children" :key="two.id">
                  <el-col :span="8">
                    <el-tag type="success" v-if="two.children.length > 0">{{
                      two.authName
                    }}</el-tag>
                    <el-tag
                      type="danger"
                      closable
                      v-if="two.children.length == 0"
                      @close="cha(item.children, index, row.id, two.id)"
                    >
                      {{ two.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i
                  ></el-col>
                  <el-col :span="8">
                    <el-row
                      v-for="(three, index) in two.children"
                      :key="three.id"
                    >
                      <el-col :span="8">
                        <el-tag
                          type="danger"
                          closable
                          @close="cha(two.children, index, row.id, three.id)"
                        >
                          {{ three.authName }}</el-tag
                        >
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <el-table-column prop="id" label="序号" width="180"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称" width="180">
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>

        <el-table-column>
          <template v-slot:header="{ row }">
            <el-button type="primary" @click="addForm = true"
              >添加角色</el-button
            >
            <div v-if="false">{{ row }}</div>
          </template>
          <el-table-column label="操作">
            <template slot-scope="{ row }">
              <el-button type="primary" @click="open(row.id)">编辑</el-button>
              <el-button type="danger" @click="del(row)">删除</el-button>
              <el-button type="warning" @click="tree(row)">分配权限</el-button>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import bread from "../../components/bread";
export default {
  components: {
    bread,
  },
  data() {
    return {
      tableData: [],

      // 添加角色
      addForm: false,
      addRole: {
        roleName: "",
        roleDesc: "",
      },

      //分配权限
      dialogRights: false,
      treeList: [], //树形组件的数据源

      treeProps: {
        children: "children",
        label: "authName",
      }, //数据源与属性对应关系

      // 回填树形的所有选中的默认id
      activeTree: [],
      // 保存选中所有的d
      saveTrees: [],

      // 修改权限的id
      roleIdd: 0,
      row: {},
    };
  },
  mounted() {
    this.query();
  },

  methods: {
    //获取角色列表
    async query() {
      let rst = await this.$http.get("roles");
      this.tableData = rst.data;
      console.log(rst);
    },

    //删除
    async del(row) {
      console.log(row.id);
      let rst = await this.$http.delete(`roles/${row.id}`);
      if (rst.meta.status == 200) {
        this.$message.success(rst.meta.msg);
        this.query();
      }
      console.log(rst);
    },

    //小叉叉删除
    async cha(arr, index, roleId, rightId) {
      let rst = await this.$http.delete(`roles/${roleId}/rights/${rightId}`);
      let { data, meta } = rst;
      if (meta.status == 200) {
        console.log(rst);
        this.$message.success(meta.msg);
        arr.splice(index, 1);
      } else {
        this.$message.error(meta.msg);
      }
    },

    // 打开添加 编辑模态框  传ID值
    async open(id) {
      this.addForm = true;
      if (id) {
        // 根据ID查询角色
        let rst = await this.$http.get(`roles/${id}`);
        this.addRole = rst.data;
        console.log(rst);
      }
    },

    //添加&编辑提交
    async save() {
      let { roleId } = this.addRole;
      // 编辑修改提交
      if (roleId) {
        let rst = await this.$http.put(`roles/${roleId}`, this.addRole);
        let { meta } = rst;
        if (meta.status == 200) {
          this.$message.success(meta.msg);
          this.query();
        }
        console.log(rst);
      } else {
        // 添加
        let rst = await this.$http.post("roles/", this.addRole);
        console.log(rst);
        if (rst.meta.status == 201) {
          this.$message.success(rst.meta.msg);
          this.query();
          this.addForm = false;
        }
        console.log(this.addRole);
      }
      this.addForm = false;
      this.addRole = {
        roleName: "",
        roleDesc: "",
      };
    },

    // 分配权限 (回填)
    async tree(row) {
      this.dialogRights = true;
      let rst = await this.$http.get("rights/tree");
      let { meta, data } = rst;
      this.roleIdd = row.id;
      this.row = row;
      console.log(rst);
      if (meta.status == 200) {
        this.treeList = data;
        // 调递归
        this.setIds(row, this.activeTree);
        console.log(row);
        // console.log(this.$refs.tree);

        //回填数据
        // 在data中定义一个数组，然后将row中所有权限的id都添加都这个数组中
        // 然后使用 this.$refs.tree.setCheckedKeys([30,115]);方法将所有权限进行回填
        this.$refs.tree.setCheckedKeys(this.activeTree);
      } else {
        this.$message.error(meta.msg);
      }
      console.log(row);
    },
    //点击分配权限的取消
    close() {
      this.dialogRights = false;
      this.activeTree = [];
     
    },

    // 递归 把所有的id全部放到this.activeTree里面
    //  定义一个递归函数，只获取最后一级菜单的id
    setIds(obj, arr) {
      if (!obj.children) {
        arr.push(obj.id);
        return;
      }
      obj.children.forEach((item) => {
        this.setIds(item, arr);
      });
    },

    //  定义一个递归函数，只获取最后一级菜单的id
    // getIds(obj, arr) {
    //   if (!obj.children) {
    //     arr.push(obj.id);
    //     return;
    //   }
    //   obj.children.forEach((item) => {
    //     this.setIds(item, arr);
    //   });
    // },

    // 清空树形
    clearTree() {
      this.$refs.tree.setCheckedKeys([]);
    },


    // 分配角色权限（保存）
    async saveTree() {
      let roleId = this.roleIdd;
      console.log(roleId);
      let sonids = this.$refs.tree.getHalfCheckedKeys();
      let dadids = this.$refs.tree.getCheckedKeys();
      this.saveTrees = [...sonids, ...dadids].join();
      // this.saveTrees = JSON.stringify(this.saveTrees);
      console.log(this.saveTrees);
      let rst = await this.$http.post(`roles/${roleId}/rights`, {
        rids: this.saveTrees,
        // rids:('34','115')
      });
      let { meta } = rst;
      if (meta.status == 200) {
        this.$message.success(meta.msg);
        this.dialogRights = false;
      }
      console.log(rst);
      this.query();
    },

    // 树形状态框发生改变时
    //  共三个参数，依次为：传递给 data 属性的数组中该节点所对应的对象、节点本身是否被选中、节点的子树中是否有被选中的节点
    // handleCheckChange(data, checked, indeterminate) {
    //   console.log(data, checked, indeterminate);
    // },

    // 树形 loadNode
    handleNodeClick(data) {
      console.log(data);
    },

    // handleCheckChange(data, checked, indeterminate) {
    //   console.log(data, checked, indeterminate);
    // },
    // handleNodeClick(data) {
    //   console.log(data);
    // },
    // loadNode(node, resolve) {
    //   if (node.level === 0) {
    //     return resolve([{ name: "region1" }, { name: "region2" }]);
    //   }
    //   if (node.level > 3) return resolve([]);

    //   var hasChild;
    //   if (node.data.name === "region1") {
    //     hasChild = true;
    //   } else if (node.data.name === "region2") {
    //     hasChild = false;
    //   } else {
    //     hasChild = Math.random() > 0.5;
    //   }

    //   setTimeout(() => {
    //     var data;
    //     if (hasChild) {
    //       data = [
    //         {
    //           name: "zone" + this.count++,
    //         },
    //         {
    //           name: "zone" + this.count++,
    //         },
    //       ];
    //     } else {
    //       data = [];
    //     }

    //     resolve(data);
    //   }, 500);
    // },
  },
};

/*
1. 拷贝 element中的树形控件
<el-tree :data="数据源属性" :props="关系属性"></el-tree>
2.在data中定义 数据源和对应数据源关系的对象,由于接口返回的数据中authName是需要显示的数据，children是子菜单，所以需要将他们进行关系对应
 treeData: [], //树形组件的数据源
      treeAttr: {
        children: "children",  
        label: "authName"
      } //数据源与属性的对应关系
3.在弹窗打开的函数中发送接口请求为treeData赋值
4.为tree控件添加 复选框的属性
          show-checkbox  :是否显示复选框
          default-expand-all ：是否展开所有的子菜单
          node-key="id" ：复选框的实际value的值
          ref="tree"  ：为ref属性，可以使用$refs获取dom
          highlight-current  ：高亮显示选中的节点
5.回填数据
    在data中定义一个数组，然后将row中所有权限的id都添加都这个数组中
    然后使用 this.$refs.tree.setCheckedKeys([30,115]);方法将所有权限进行回填
*/
</script>

<style lang="less" scoped>
/deep/ .el-row {
  margin-left: 120px;
}
</style>